<?php

namespace App\Api\Controllers;

use App\Models\UserLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use App\Models\Recharge;

class PayController extends Controller
{

    public function notify(){
        $alipay = Pay::alipay(config('pay.alipay'));
        try{
            $data = $alipay->verify(); // 是的，验签就这么简单！
          //  \Illuminate\Support\Facades\Log::error('验签'.json_encode($data));
            $recharge = Recharge::where(['no'=>$data->out_trade_no,'status'=>0,'pay_status'=>0])->first();
            if($recharge){
                $recharge->status = 1;
                $recharge->pay_status = 1;
                $recharge->pay_at = Carbon::now();
                if($recharge->save()){
                    (new UserLog())->change($recharge->amount,$recharge->user_id,'balance',12,'用户充值');
                }
            }
            Log::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error($e->getMessage());
           // $e->getMessage();
        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
    }
}
